<?php

namespace qiniu;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use think\facade\Env;
use think\facade\Log;

class OssQiniu {

    private $accessKey;
    private $secretKey;
    private $bucket = '';

    /**
     * 构造函数
     * Oss constructor.
     */
    public function __construct() {
        $this->accessKey = Env::get('ossqiniu.access_key');
        $this->secretKey = Env::get('ossqiniu.secret_key');
        $this->bucket = Env::get('ossqiniu.bucket');
        require 'autoload.php';
    }

    /***
     * @desc 将本地图片上传到远程服务器
     * @param $fileName
     * @param $pathName
     * @param $cdn
     * @return mixed|string
     */
    public function uploadImage($fileName, $pathName, $cdn = 'NO') {
        try {
            $auth = new Auth($this->accessKey, $this->secretKey);

            if ($cdn === 'YES'){
                $endPoint=Env::get('oss.url');
            }else{
                $ossBucketManager = new BucketManager($auth);
                $endPoint='http://'.$ossBucketManager->domains($this->bucket)[0][0];
            }

            $token = $auth->uploadToken($this->bucket);
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $fileName, $pathName);

            return $endPoint . '/' . $ret['key'];
        } catch (\Exception $e) {
            Log::write("上传本地图片到OssQiniu服务器错误信息" . print_r($e));
        }
    }
}